package com.shop.mqConsumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class EmailConsumer {
    @Autowired
    private JavaMailSender javaMailSender;
    private final String SEND_EMAIL_NUMBER = "1063556012@qq.com";
    @RabbitListener(queues = "email_queue")
    public void emailHandle(Map<String,String> emailMap, Channel channel, Message message) throws IOException {
        try{
            sendEmail(emailMap.get("email"),emailMap.get("subject"),emailMap.get("text"));
        }catch(Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
    private void sendEmail(String email, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(SEND_EMAIL_NUMBER);
        message.setTo(email);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
    }
}
